<template>
  <el-row style="display: flex; height: 200px; margin: 20px;" gutter="10">
    <!-- Left Card -->
    <el-col :style="{ flex: expandedCard === 'left' ? '23' : '1', transition: 'flex 0.5s ease-in-out' }">
      <el-card shadow="hover" class="card-height">
        <el-button style="float: right; padding: 3px 0;" type="text" @click="toggleLeftCard">
          <el-icon v-if="expandedCard !== 'left'" size="16">
            <Expand/>
          </el-icon>
          <el-icon v-else size="16">
            <Fold/>
          </el-icon>
        </el-button>

        <el-form :inline="true" label-position="left">
          <!-- 基础信息 -->
          <el-row :gutter="10" style="width: 100%;">
            <el-col :span="8">
              <el-form-item label="电影名称" style="width: 100%;">
                <el-select v-model="searchFrom.filmName"
                           filterable
                           remote
                           clearable
                           placeholder="请输入电影名称">
                  <el-option
                      v-for="item in tableData"
                      :key="item.value"
                      :label="item.filmName"
                      :value="item.filmName">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-col>
            <el-col :span="8">
              <el-form-item label="电影标签" style="width: 100%;">
                <el-select v-model="searchFrom.tag"
                           filterable
                           remote
                           clearable
                           placeholder="请输入标签">
                  <el-option
                      v-for="item in tagList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上映时间" style="width: 100%;">
                <el-select v-model="searchFrom.releaseYear" placeholder="请选择">
                  <el-option
                      v-for="item in releaseDateList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 扩展信息 -->
          <el-collapse-transition>
            <div v-if="expandedCard === 'left'" style="width: 100%;">
              <el-row :gutter="10" style="width: 100%;">
                <el-col :span="8">
                  <el-form-item label="电影状态" style="width: 100%;">
                    <el-select v-model="searchFrom.status" placeholder="请选择状态">
                      <el-option label="上架" value="1"/>
                      <el-option label="下架" value="0"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="导演名字" style="width: 100%;">
                    <el-select v-model="searchFrom.directorId"
                               filterable
                               remote
                               clearable
                               placeholder="请输入导演姓名">
                      <el-option
                          v-for="item in directorList"
                          :key="item.value"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="电影地区" style="width: 100%;">
                    <el-select v-model="searchFrom.region"
                               filterable
                               remote
                               clearable
                               placeholder="请选择地区">
                      <el-option
                          v-for="item in regionList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-transition>
        </el-form>
        <div style="position: absolute; bottom: 20px; right: 30px;">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="search">查询</el-button>
        </div>
      </el-card>
    </el-col>

    <!-- Right Card -->
    <el-col :style="{ flex: expandedCard === 'right' ? '23' : '1', transition: 'flex 0.5s ease-in-out' }">
      <el-card shadow="hover" class="card-height">
        <div v-if="expandedCard !== 'left'" class="card-content">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button type="success" class="btn" @click="addFilm">添加影片</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" class="btn" @click="router.push('/subject')">电影专题</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button type="primary" class="btn" @click="router.push('/director')">导演列表</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" class="btn" @click="router.push('/actor')">演员列表</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button type="primary" class="btn" @click="exportFilm">导出电影信息</el-button>
            </el-col>
          </el-row>
          <div v-if="expandedCard !== 'left'" style="position: absolute;top: 10px;right: 40px">
            <img src="/img/page/摄影机.png"
                 alt="摄影机"
                 class="image-fade-in"
                 style="width: 150px;height: auto;float: right;margin-top: 10px;margin-right: 20px;">
          </div>
        </div>

        <el-button style="position: absolute;top: 80px;right: 15px;"
                   type="text" @click="restoreOriginalSize">
          <el-icon v-if="expandedCard !== null" size="16">
            <Fold/>
          </el-icon>
        </el-button>
      </el-card>
    </el-col>
  </el-row>
  <div></div>
  <el-card style="margin: 20px;height: 58vh">
    <el-scrollbar>
      <el-table :data="paginatedData"
                stripe
                style="margin-top: 20px;height: 360px;width: 100%">
        <el-table-column fixed type="index" label="编号" width="80" align="center"/>
        <el-table-column fixed label="电影名称" prop="filmName" align="center" width="200"/>
        <el-table-column label="电影标签" prop="tag" width="200px" align="center"
                         :formatter="tagFormatter"/>
        <el-table-column label="电影导演" prop="directorName" align="center"/>
        <el-table-column label="上映时间" prop="releaseDate" align="center" width="100"/>
        <el-table-column label="上映地区" prop="region" align="center"
                         :formatter="regionFormatter"/>
        <el-table-column label="发布状态" prop="releaseStatus" align="center">
          <template #default="scope">
            <span v-if="scope.row.releaseStatus === '1'">上映</span>
            <span v-else>
              <el-button type="primary" link
                         @click="uploadFilm(scope.row.id)"
              >预告</el-button>
               </span>
          </template>
        </el-table-column>
        <el-table-column label="电影上架状态" prop="status" align="center">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="updateStatus(scope.row.id, scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" align="center">
          <template #default="scope">
            <el-button link type="danger" @click="deleteFilm(scope.row.id)">删除</el-button>
            <el-button link type="primary" @click="filmDetails(scope.row.id)">查看详情</el-button>
          </template>
        </el-table-column>

      </el-table>
    </el-scrollbar>
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />
  </el-card>

  <el-dialog v-model="uploadFilmVisible"
             style="width: 600px; padding: 30px;height: 340px;position: relative"
             title="添加电影" >
       <el-form>
         <el-form-item label="电影视频"
                       style="margin-top: 40px">
           <el-upload
               v-model:file-list="filmFileList"
               class="upload-demo"
               v-model:action="saveFilmUrl"
               multiple
               :on-remove="removeFilm"
               :on-change="handleVideoChange"
               :on-preview="handleVideoPreview"
               :limit="1"
           >
             <el-button style="width: 150px;"
                        type="primary">上传视频
             </el-button>
             <template #tip>
               <div class="el-upload__tip">
                 上传视频文件，支持格式：mp4，文件大小不超过3GB
               </div>
             </template>
           </el-upload>
         </el-form-item>
         <el-dialog style="width: 600px; padding: 30px" v-model="filmVisible">
           <video :src="videoUrl"
                  style="width: 540px;"
                  controls/>
         </el-dialog>
       </el-form>
    <template #footer>
      <el-button type="primary"
                 style="position: absolute;right: 30px;bottom: 30px"
                 @click="saveFilm">保存</el-button>
      <el-button @click="cancel"
                 style="position: absolute;right: 100px;bottom: 30px"
      >取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router";
import * as XLSX from "xlsx";

const expandedCard = ref(null);

const toggleLeftCard = () => {
  if (expandedCard.value === 'left') {
    expandedCard.value = null;
  } else {
    expandedCard.value = 'left';
  }
};

const restoreOriginalSize = () => {
  expandedCard.value = null;
};
const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(6); // 每页显示6条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};

const tagList = ref([]);
const regionList = ref([]);
const releaseDateList = ref([]);
onMounted(() => {
  loadDictOptions(tagList, 'tag');
  loadDictOptions(regionList, 'nationality');
  loadDictOptions(releaseDateList, 'year');
  searchDirector()
});
const tagFormatter = (row, column, cellValue, index) => {
  if (!tagList.value || !cellValue) {
    return cellValue;
  }
  // 将斜杠分隔的字符串转换为数组
  const tagsArray = cellValue.split('/');
  // 查找并替换每个标签值
  const formattedTags = tagsArray.map(tagValue => {
    for (let item of tagList.value) {
      if (item.value === tagValue) {
        return item.label; // 返回对应的汉字内容
      }
    }
    return tagValue; // 如果没有找到对应的汉字内容，则保留原始值
  });
  // 将格式化后的标签数组重新组合为字符串
  return formattedTags.join(' ');
};

const regionFormatter = (row, column, cellValue, index) => {
  if (!regionList.value) {
    return cellValue;
  }
  for (let item of regionList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const tagDataFormatter = (row, column, cellValue, index) => {
  if (!tagList.value) {
    return cellValue;
  }
  for (let item of tagList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const directorList = ref([]);
const searchDirector = () => {
  axios.get(BASE_URL + '/v1/director/select')
      .then((response) => {
        if (response.data.code === 2000) {
          directorList.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}

const searchFrom = ref({
  filmName: '',
  tag: '',
  releaseYear: '',
  status: '',
  directorId: '',
  region: '',
});

const search = () => {
  let data = qs.stringify(searchFrom.value);
  console.log(data);
  axios.get(BASE_URL + '/v1/film/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
const resetSearch = () => {
  searchFrom.value = {
    filmName: '',
    tag: '',
    releaseDate: '',
    status: '',
    directorId: '',
    region: '',
  };
  search();
};
onMounted(() => {
  search();
})

const addFilm = () => {
  router.push('insert')
}
const filmDetails = (id) => {
  router.push('/details?id=' + id)
}

const exportFilm = () => {
  search();
  try {
    // 定义固定的表头
    const headers = [
      'id', 'filmName', 'englishName', 'region', 'releaseDate', 'releaseYear',  'duration', 'synopsis',
      'directorId', 'poster', 'filmUrl', 'status', 'releaseStatus', 'createTime', 'updateTime'

    ];

    // 将 JSON 数据转换为二维数组
    const data = tableData.value.map(film => headers.map(header => film[header]));

    // 检查数据有效性
    if (!data.length || !data.every(row => Array.isArray(row) && row.length === headers.length)) {
      errorInfo('导出失败：数据为空');
      return;
    }

    // 直接在数据前插入表头
    data.unshift(headers);

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 动态生成文件名
    // 获取当前日期并格式化为 YYYY_MM_DD 格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(now.getDate()).padStart(2, '0');

    const formattedDate = `${year}_${month}_${day}`;
    const fileName = `film_export_${formattedDate}.xlsx`;

    // 导出Excel文件
    XLSX.writeFile(wb, fileName);

    // 提示用户导出成功
    OKInfo('导出成功');
  } catch (error) {
    errorInfo('导出失败，请检查控制台日志');
  }
}

const deleteFilm = (id) => {
  ElMessageBox.confirm('确定删除该电影吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/film/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            search();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        });
  }).catch(() => {
    Info('已取消删除')
  })
}
const updateStatus = (id, status) => {
  axios.put(BASE_URL + '/v1/film/update/status/' + id + '/' + status)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('更新成功!')
          search();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      });
}
const filmId = ref('');
const uploadFilm = (id) => {
 uploadFilmVisible.value = true;
 filmId.value = id;
}
const uploadFilmVisible = ref(false);
/**视频上传相关代码开始**/
const filmFileList = ref([]);
const isShow = ref(false);
const saveFilmUrl = ref(BASE_URL + '/v1/filmUrl/upload');
const removeFilm = (uploadFile, uploadFiles) => {
  let filmUrl = uploadFile.response.data;
  axios.post(BASE_URL + '/v1/filmUrl/remove?filmUrl=' + filmUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
          isShow.value = false;
        }
      })
}
const videoUrl = ref('');
const handleVideoChange = (uploadFile) => {
  const file = uploadFile.raw;
  if (!file) return;
  videoUrl.value = URL.createObjectURL(file);
}
const filmVisible = ref(false);
const handleVideoPreview = (uploadFile) => {
  filmVisible.value = true;
}

/**视频上传相关代码结束**/

const saveFilm = () => {
 ElMessageBox.confirm('确定上传该视频吗？', '提示', {
   customClass: 'custom-message-box',
   confirmButtonText: '确定',
   cancelButtonText: '取消',
   type: 'warning',
   draggable: true,
 }).then(() => {
   let data = qs.stringify({
     filmId: filmId,
     releaseStatus: 1,
     filmUrl: filmFileList.value[0].response.data,
   });
   axios.put(BASE_URL + '/v1/film/update', data)
       .then((response) => {
         if (response.data.code === 2000) {
           ElMessage.success('上传成功!');
           uploadFilmVisible.value = false;
           search();
         } else {
           ElMessage({
             message: response.data.msg,
             type: 'error',
             showClose: true,
             center: true,
           });
         }
       });
 }).catch(() => {

 })
}
const cancel = () => {
  Info('已取消上传');
  uploadFilmVisible.value = false;
  filmFileList.value = [];
}
</script>

<style scoped>
.card-height {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.card-content {
  flex-grow: 1;
  width: 300px;
}

.btn {
  height: 40px;
  width: 90%;
  margin-top: 10px;
}

</style>